import { produce } from "immer";
import { type FC, memo, useState } from "react";
import classNames from "classnames";
import { useDebounceFn, useMemoizedFn } from "ahooks";
import contentStyle from "../index.module.scss";
import styles from "./index.module.scss";
import Slider from "./slider";
import { updateCustomization } from "@/service";
import { useCustomizationStore } from "@/src/providers/customization-store-provider";
import { usePersonalDetailStore } from "@/src/providers/personal-detail-store-provider";

interface IndexProps {
  onlySpace?: boolean;
}
const Index: FC<IndexProps> = ({ onlySpace }) => {
  const { customization, updateSpacing, addCustomization } =
    useCustomizationStore(
      (state) => state,
      (o, n) => {
        return o.customization.spacing === n.customization.spacing;
      }
    );

  const { personalDetails } = usePersonalDetailStore(
    (state) => state,
    (o, n) => {
      return o.personalDetails.id === n.personalDetails.id;
    }
  );
  let init = [
    { name: "fontSize", label: "字体大小" },
    { name: "lineHeight", label: "行高" },
    { name: "marginHorizontal", label: "水平边距" },
    { name: "marginVertical", label: "垂直边距" },
    { name: "spacingFactor", label: "模块间距" },
  ];
  if (onlySpace) {
    init = [
      { name: "marginHorizontal", label: "水平边距" },
      { name: "marginVertical", label: "垂直边距" },
      { name: "spacingFactor", label: "模块间距" },
    ];
  }
  const [sliders] = useState(init);

  const change = (data) => {
    updateSpacing(data);
  };
  const updateValue = (params) => {
    return updateCustomization({
      ...params,
    });
  };
  const { run } = useDebounceFn(
    (data) => {
      updateValue({
        updates: [
          {
            path: data.path,
            value: data.value,
          },
        ],
        id: customization.id,
      });
    },
    {
      wait: 1000,
    }
  );
  const onChange = useMemoizedFn((v, name) => {
    const data = produce(customization.spacing, (draft) => {
      draft[name] = v;
    });
    change(data);
    if (customization.id) {
      run({
        path: `spacing.${name}`,
        value: v,
      });
    } else if (personalDetails.id) {
      addCustomization(personalDetails.id);
    }
  });
  return (
    <div className={classNames(styles.spacing, contentStyle.card)}>
      <h1 className={contentStyle.title} style={{ marginBottom: "30px" }}>
        间距
      </h1>
      {sliders.map((s) => {
        return (
          <div key={s.name} style={{ marginBottom: "10px" }}>
            <Slider
              value={(customization.spacing as any)[s.name]}
              item={s}
              onChange={(v) => onChange(v, s.name)}
            />
          </div>
        );
      })}
    </div>
  );
};

export default memo(Index, () => {
  return true;
});
